/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SelectingDatabaseUser.java
 *
 * Created on 2011-04-18, 21:40:10
 */
package bsk_dac.database;

import bsk_dac.MainDACFrame;
import bsk_dac.accesscontrol.TableAccess;
import com.mysql.jdbc.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author przemo
 */
public class SelectingDatabaseUserFrame extends javax.swing.JFrame {

    MainDACFrame mainFrame;

    public SelectingDatabaseUserFrame(MainDACFrame mainFrame) {
        initComponents();
        this.mainFrame = mainFrame;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nameField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        loginButton = new javax.swing.JButton();
        passwordField = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Zaloguj się do bazy danych");
        setLocationByPlatform(true);

        jLabel1.setText("Użytkownik");

        nameField.setText("jarek");

        jLabel2.setText("Hasło");

        loginButton.setText("Zaloguj");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });

        passwordField.setText("root");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(loginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(22, 22, 22)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(nameField)
                            .addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))))
                .addContainerGap(69, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(loginButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed

        MainDACFrame.adminMode = false;
        MainDACFrame.isAdmin = false;
        Connection conn;
        //Próba zaloogowania jako admin
        if (nameField.getText().equals("admin2") && passwordField.getText().equals("root")) {
            conn = null;
            try {
                Properties connectionProps = new Properties();
                connectionProps.put("user", "marek");
                connectionProps.put("password", "root");
                DatabaseUser.userName = nameField.getText();
                DatabaseUser.userPassword = nameField.getText();
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db:jforum", connectionProps);
                MainDACFrame.conn = conn;
                System.out.println("Connected to database");
            }catch(SQLException se){
                se.printStackTrace();
            }
            mainFrame.adminMode = true;
            this.dispose();
            mainFrame.setVisible(true);
            mainFrame.loadAdminMode();
            System.out.println("Zalogowany jako admin");
        } else {
            //Próba zalogowania jako zwykły użytkownik
            conn = null;
            try {
                Properties connectionProps = new Properties();
                connectionProps.put("user", "marek");
                connectionProps.put("password", "root");
                DatabaseUser.userName = nameField.getText();
                DatabaseUser.userPassword = nameField.getText();
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db:jforum", connectionProps);
                MainDACFrame.conn = conn;
                System.out.println("Connected to database");

                if(DatabaseFacade.getAdmin().equals(nameField.getText())){
                    MainDACFrame.isAdmin = true;
                }

                Statement stmt = null;
                String query = "select * from users where login='" + nameField.getText() + "';";
                stmt = (Statement) conn.createStatement();
                ResultSet rs = stmt.executeQuery(query);
                String userPass = null;

                while (rs.next()) {
                    userPass = rs.getString("pass");
                }
                if (userPass == null || !userPass.equals(passwordField.getText())) {
                    throw new SQLException();
                }


            } catch (SQLException ex) {
                showMessageBox("Błąd logowania", "Podałeś złe haslo, bądź login");
                try {
                    conn.close();
                } catch (SQLException ex1) {
                    Logger.getLogger(SelectingDatabaseUserFrame.class.getName()).log(Level.SEVERE, null, ex1);
                }
            } finally {
                this.dispose();
                mainFrame.setVisible(true);
                mainFrame.loadPrivilegesPanel();
            }
        }
    }//GEN-LAST:event_loginButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton loginButton;
    private javax.swing.JTextField nameField;
    private javax.swing.JPasswordField passwordField;
    // End of variables declaration//GEN-END:variables

    private void showMessageBox(String title, String content) {
        JOptionPane.showMessageDialog(null, content, title, JOptionPane.ERROR_MESSAGE);
    }
}
